package com.kehutong.payfees.service.receipt;

import com.kehutong.common.DeptService;
import com.kehutong.common.Java8TimeUtils;
import com.kehutong.common.dto.DeptDTO;
import com.kehutong.common.urlconfig.FileUrlConfig;
import com.kehutong.common.util.Token;
import com.kehutong.payfees.entity.ChargeBill;
import com.kehutong.payfees.entity.ChargeBillItem;
import com.kehutong.payfees.entity.ChargeGenerate;
import com.kehutong.payfees.entity.receipt.PayBillManage;
import com.kehutong.payfees.entity.receipt.PayBillRecord;
import com.kehutong.payfees.entity.receipt.ReceiptOrder;
import com.kehutong.payfees.entity.receipt.ReceiptStatistics;
import com.kehutong.payfees.service.worker.ChargeWorkerServiceImpl;
import com.kehutong.payfees.util.BasicClient;
import com.kehutong.payfees.util.PdfTableUtil;
import com.kehutong.payfees.util.PdfUtil;
import org.coraframework.converter.util.StringUtil;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONArray;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.orm.jdbc.Page;
import org.coraframework.orm.jdbc.execute.entity.FindPage;

import java.io.File;
import java.io.FileOutputStream;
import java.util.*;

/**
 * @program: kht
 * @description: 缴费管理
 * @author: joneron
 * @create: 2021/5/28
 **/
public class PayManageServiceImpl {

    private static final Logger logger = LoggerFactory.getLogger(PayManageServiceImpl.class);

    @Inject
    private JdbcSession jdbcSession;

    @Inject
    BasicClient basicClient;
    @Inject
    DeptService deptService;
    @Inject
    FileUrlConfig fileUrlConfig;


    public Page<PayBillManage> findPage(JSONObject jsonObject) {

        FindPage<PayBillManage> find = jdbcSession.findPage(PayBillManage.class)
                .eq("deleted", false)
                .eq(jsonObject,"status")
                .like(jsonObject,"payBillName")
                .like(jsonObject,"communityList")
                .order("createTime", "desc");

        find.page(jsonObject);

        return find.exe();
    }

    public List<PayBillManage> findList(JSONObject jsonObject) {

        List<PayBillManage> receiptList = jdbcSession.findArray(PayBillManage.class)
                .eq("deleted", false)
                .eq("status",true)
                .like(jsonObject,"communityList")
                .exe();

        return receiptList;
    }

    public Integer save(PayBillManage entity) {

        return jdbcSession.insert(entity);
    }

    public Integer update(PayBillManage entity) {
        return jdbcSession.updateById(entity);
    }

    public Integer deleteById(String id) {
        PayBillManage result = Pool.get(PayBillManage.class, id);
        if (result != null) {
            result.setDeleted(true);
            jdbcSession.updateById(result);
        }
        return 1;
    }

    public Page<PayBillRecord> findPayPage(JSONObject jsonObject) {

        FindPage<PayBillRecord> find = jdbcSession.findPage(PayBillRecord.class)
                .eq("deleted", false)
                .eq(jsonObject,"payBillNo")
                .eq(jsonObject,"communityNo")
                .like(jsonObject,"createTime")
                .order("createTime", "desc")
                .page(jsonObject);

        return find.exe();
    }

    public List<ReceiptStatistics> groupData(JSONObject jsonObject, Token token) throws Exception {

        String date1 = "2021-06-01"; //本月
        String date2 = "2021-05-01"; //上个月
        String strDate = jsonObject.getString("statistTime");
        if(null != strDate){
            date1 = strDate.substring(0,7);
            int num = Integer.parseInt(date1.substring(5,7))-1;
            date2 = date1.substring(0,5) + String.format("%02d", num);
        }else {
            //2.根据小区统计数据
            Calendar cal = Calendar.getInstance();
            int year = cal.get(Calendar.YEAR);
            int monthly = cal.get(Calendar.MONTH) + 1;
            int month = cal.get(Calendar.MONTH);
            //本月 (0 代表前面补充0,10代表长度为10,d 代表参数为正数型)
            date1 = year +"-"+ String.format("%02d", monthly);
            //上一个月 (0 代表前面补充0,10代表长度为10,d 代表参数为正数型)
            date2 = year +"-"+String.format("%02d", month);
        }

        List<ReceiptStatistics> statList = new ArrayList<>();
        String data3 = date1;
        String data4 = date2;

        //Map<String,JSONObject> communityMap = basicClient.getCommunityMap(token);

        JSONArray array = jsonObject.getJSONArray("communitys");

        for (int i = 0; i < array.size(); i++) {
            String communityId = array.getString(i);

            List<PayBillRecord> receiptList1 = jdbcSession.findArray(PayBillRecord.class)
                    .like("createTime",data3)
                    .eq("communityNo",communityId).exe();

            List<PayBillRecord> receiptList2 = jdbcSession.findArray(PayBillRecord.class)
                    .like("createTime",data4)
                    .eq("communityNo",communityId).exe();

            List<PayBillRecord> receiptListAll = jdbcSession.findArray(PayBillRecord.class)
                    .eq("communityNo",communityId).exe();

            //String viewName = v.get("name");

            ReceiptStatistics receipt = new ReceiptStatistics();
            receipt.setCommunityName(communityId);
            receipt.setLastMonthNum(receiptList2.size());
            receipt.setMonthlyNum(receiptList1.size());
            receipt.setTotalNum(receiptListAll.size());

            statList.add(receipt);

        }

        return statList;
    }


    //生成PDF账单
    /**
     * 生成PDF文件
     * @param
     * @param
     * @return
     */
    public Object generatePdf(ChargeBill chargeBill, String ownerName) throws Exception {

        String communityNo = chargeBill.getCommunityNo();

        logger.info("自动生成PDF文件！小区编号：{}",communityNo);

        PayBillManage receiptManage = null;
        try {
            //1、查询电子签章,判断是否有配置收据模板及公章
            receiptManage = jdbcSession.findOne(PayBillManage.class)
                    .like("communityList", communityNo)
                    .eq("status", true).exe();

            if (null == receiptManage) {
                logger.error("{}小区未设置缴费单模板！", communityNo);
                return Result.error(0, "请先去设置或开启缴费单模板！");
            }
        }catch (Exception e){
            return Result.error(0, "缴费单模板设置不合理，同一个小区只能配置一个模板！");
        }

        //3、查询账单数据
        Map<String,Object> mapParam = new LinkedHashMap<String,Object>();
        mapParam.put("company", receiptManage.getTitleName());
        mapParam.put("community",chargeBill.getCommunityName());
        mapParam.put("realName",ownerName);  //房东姓名
        // 显示： 12栋-1801
        StringBuffer houseInfo = new StringBuffer();
        houseInfo.append(chargeBill.getBuildingName()).append("-");
        if(StringUtil.isNotBlank(chargeBill.getUnitName())){
            houseInfo.append(chargeBill.getUnitName()).append("-");
        }
        houseInfo.append(chargeBill.getHouseName());
        mapParam.put("houseInfo",houseInfo);  //房号
        mapParam.put("datePay", Java8TimeUtils.dateShort());
        String receiptNo = PdfTableUtil.generateNumber("JFD");
        mapParam.put("receiptNO","NO."+receiptNo);
        //上传的签章图片
        String fileImg = fileUrlConfig.getFile(receiptManage.getSealImgId());
        mapParam.put("sealFile",fileImg);
        mapParam.put("totalAmount",chargeBill.getTotal());
        mapParam.put("content",chargeBill.getBillDateFrom() +"至"+chargeBill.getBillDateTo());
        //type : 收据：receipt,缴费单：payBill
        mapParam.put("type","payBill");
        mapParam.put("remark",receiptManage.getRemark());

        //查询账单项
        List<ChargeBillItem> billItems = jdbcSession.findArray(ChargeBillItem.class).eq("billNo", chargeBill.getId()).exe();
        mapParam.put("dataList",billItems);

        //4、生成PDF文件
        PdfUtil pdfUtil = new PdfUtil();
        byte[] pdf = pdfUtil.execute(mapParam);

        String pdfName = receiptNo+".pdf";
        File file = new File(pdfName);

        FileOutputStream outputFileStream = new FileOutputStream(file);
        outputFileStream.write(pdf);
        outputFileStream.close();

        //保存收据单数据
        PayBillRecord receipt =  Pool.newInstance(PayBillRecord.class);
        receipt.setPayBillNo(receiptNo); //生成自定义编号
        receipt.setPayOrderNo(chargeBill.getId());
        JSONObject jsonObject =  fileUrlConfig.sendFile(file, http->{ });
        String fileId = jsonObject.getJSONObject("data").getString("id");
        receipt.setFileId(fileId);
        receipt.setHouseInfo(houseInfo.toString());
        receipt.setCommunityNo(communityNo);
        receipt.setDepartmentName(chargeBill.getDepartmentName());
        receipt.setDepartmentNo(chargeBill.getDepartmentNo());
        receipt.setDepartmentNos(chargeBill.getDepartmentNos());

        jdbcSession.insert(receipt);

        //文件上传成功后自动删除
        if (file.exists() && file.isFile() && file.delete() == true) {
            logger.info("{}本地文件已经删除!",pdfName);
        }

        //代表已经生成过了
        chargeBill.setPayFileId(fileId);

        return jdbcSession.updateById(chargeBill);
    }


}
